﻿using System;
using System.Data;
using System.Collections;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Net.Mail;
using System.Net.Configuration;
using VINETLIFE.BL;
using VINETLIFE.DO;
using System.Web.Caching;
using System.Collections.Generic;
using System.Web.Script.Serialization;

namespace VINETLIFE
{
    public class Ultility
    {
        public static void Alert(string msg, string url)
        {
            // Cleans the message to allow single quotation marks
            string cleanMessage = msg.Replace("'", "\\'");
            string script = "<script type=\"text/javascript\">alert('" + cleanMessage + "');location='" + url + "';</script>";

            // Gets the executing web page
            Page page = HttpContext.Current.CurrentHandler as Page;

            // Checks if the handler is a Page and that the script isn't allready on the Page
            if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("Ultility"))
            {
                page.ClientScript.RegisterClientScriptBlock(typeof(Ultility), "Ultility", script);
            }
        }
        public static string WebTitle()
        {
            return new sysConfigBL().Select(new sysConfigDO { ConfigID = 1 }).ConfigValue.ToString();
        }
        public static void Alert(string msg)
        {
            // Cleans the message to allow single quotation marks
            string cleanMessage = msg.Replace("'", "\\'");
            string script = "<script type=\"text/javascript\">alert('" + cleanMessage + "');</script>";

            // Gets the executing web page
            Page page = HttpContext.Current.CurrentHandler as Page;

            // Checks if the handler is a Page and that the script isn't allready on the Page
            if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("Ultility"))
            {
                page.ClientScript.RegisterClientScriptBlock(typeof(Ultility), "Ultility", script);
            }
        }
        public static void RedirectPage(string url)
        {
            // Cleans the message to allow single quotation marks
            string script = "<script type=\"text/javascript\">location='" + url + "';</script>";

            // Gets the executing web page
            Page page = HttpContext.Current.CurrentHandler as Page;

            // Checks if the handler is a Page and that the script isn't allready on the Page
            if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("Ultility"))
            {
                page.ClientScript.RegisterClientScriptBlock(typeof(Ultility), "Ultility", script);
            }
        }
        public static string EncryptMd5(string str)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] b1 = UTF8Encoding.UTF8.GetBytes(str);
            byte[] b2 = md5.ComputeHash(b1);
            string encrypted = BitConverter.ToString(b2).Replace("-", "");
            return encrypted;
        }
        public static void GvDatabinder(DevExpress.Web.ASPxGridView.ASPxGridView gv, object obDataSource)
        {
            gv.DataSource = obDataSource;
            gv.DataBind();
        }
        public void SeoDefault(string title)
        {

        }

        public static void DevCboDatabinder(DevExpress.Web.ASPxEditors.ASPxComboBox cbo, string dtField, string TxtField, object obDataSource)
        {
            cbo.DataSource = obDataSource;
            cbo.TextField = TxtField;
            cbo.ValueField = dtField;
            cbo.DataBind();
            cbo.Items.Insert(0, cbo.Items.Add("---Select All---", "All"));
            cbo.SelectedIndex = 0;

        }
        public static bool Email(string Email)
        {
            return Regex.IsMatch(Email, @"^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$");
        }

        public static void ddlDatabinder(DropDownList ddl, string DataField, string TextField, object obDataSource)
        {
            ddl.DataSource = obDataSource;
            ddl.DataValueField = DataField;
            ddl.DataTextField = TextField;
            ddl.DataBind();
        }
        public static string Change_AV(string ip_str_change)
        {
            if (string.IsNullOrEmpty(ip_str_change)) return "index.html";
            Regex v_reg_regex = new Regex("\\p{IsCombiningDiacriticalMarks}+");
            string v_str_FormD = ip_str_change.Normalize(NormalizationForm.FormD);
            string rt = v_reg_regex.Replace(v_str_FormD, String.Empty).Replace('\u0111', 'd').Replace('\u0110', 'D').Replace(" ", "-").Replace("/", "-").Replace("?", "-");
            rt = rt.Replace("\\", "-").Replace("'", "-").Replace(":", "-").Replace("\"", "-").Replace(".", "").Replace("&", "-").Replace("(", "-").Replace(")", "-").Replace(",", "-").Replace("–", "");

            rt = rt.Replace("--", "-");
            return rt;
        }

        public static string Change_AVNohtml(string ip_str_change)
        {
            if (string.IsNullOrEmpty(ip_str_change)) return "index.html";
            Regex v_reg_regex = new Regex("\\p{IsCombiningDiacriticalMarks}+");
            string v_str_FormD = ip_str_change.Normalize(NormalizationForm.FormD);
            string rt = v_reg_regex.Replace(v_str_FormD, String.Empty).Replace('\u0111', 'd').Replace('\u0110', 'D').Replace(" ", "-").Replace("/", "-");
            rt = rt.Replace("\\", "-").Replace("'", "-").Replace(":", "-").Replace("&", "-");
            return rt;

        }
        public static string GetPrice(object e)
        {
            string price = "";
            try
            {
                int productID = int.Parse(e.ToString());

                cmsProductDO objProduct = new cmsProductBL().Select(new cmsProductDO() { ProductID = productID });

                if (objProduct.IsPromotion)
                {
                    if (objProduct.SalePrice > 0)
                    {
                        price = string.Format("{0:0,0}", objProduct.SalePrice) + " đ";
                    }
                    else
                    {
                        price = "Liên hệ";
                    }
                }
                else
                {
                    if (objProduct.Price > 0)
                    {
                        price = string.Format("{0:0,0}", objProduct.Price) + " đ";
                    }
                    else
                    {
                        price = "Liên hệ";
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }
            return price;
        }
        public static string GetPriceNormal(object e)
        {
            string price = "";
            try
            {
                long lPrice = 0;
                lPrice = long.Parse(e.ToString());
                if (lPrice > 0)
                {
                    price = string.Format("{0:#,#}", lPrice) + " đ";
                }
                else
                {
                    price = "Liên hệ";
                }
            }
            catch (Exception)
            {
                throw;
            }
            return price;
        }
        public static string GetSalePriceNormal(object isSale, object price)
        {
            string returnPrice = "";
            try
            {
                bool lIsSale = false;
                lIsSale = bool.Parse(isSale.ToString());
                // Co khuyen mai
                if (lIsSale)
                {
                    long lPrice = 0;
                    lPrice = long.Parse(price.ToString());
                    if (lPrice < 0)
                    {
                        returnPrice = "";
                    }
                    else
                    {
                        returnPrice = string.Format("{0:#,#}", lPrice) + " đ";
                    }
                }
                else
                {
                    returnPrice = "";
                }

            }
            catch
            {

                returnPrice = "";
            }
            return returnPrice;
        }
        public static string TagDataBindding(string tag, string aclass)
        {
            string urltag = "/Tags/1/";
            string TotalTag = "";
            TotalTag = tag;
            DataTable dt = new DataTable();
            dt.Columns.Add("TagItem");
            string tagItem = "";
            DataRow row;
            string fulltag = "";
            if (String.IsNullOrEmpty(TotalTag))
                return null;
            for (int i = 0; i < TotalTag.Length; i++)
            {
                if (TotalTag[i] != ',')
                {
                    tagItem += TotalTag[i];
                }
                else
                {
                    row = dt.NewRow();
                    row[0] = CreateTagURL(tagItem, urltag, aclass);
                    dt.Rows.Add(row);
                    tagItem = "";
                }
                if (tagItem.Length > 0)
                    if (i == TotalTag.Length - 1 && TotalTag[i] != ',')
                    {
                        row = dt.NewRow();
                        row[0] = CreateTagURL(tagItem, urltag, aclass);
                        dt.Rows.Add(row);
                        tagItem = "";
                    }
            }
            foreach (DataRow dr in dt.Rows)
            {
                fulltag = fulltag + dr["TagItem"].ToString();
            }
            return fulltag;
        }

        public static string CreateTagURL(string tag, string urltag, string aclass)
        {
            tag = tag.Replace(".", "");
            return "<a href='" + urltag + tag + ".html'>" + tag + "</a>,&nbsp;";
        }

        public static void bindatalist(DataTable dt, Repeater rpt, ImageButton cmdPrev, ImageButton cmdNext, int CurrentPage)
        {
            PagedDataSource objPds = new PagedDataSource();
            objPds.DataSource = dt.DefaultView;
            objPds.AllowPaging = true;
            objPds.PageSize = 10;
            objPds.CurrentPageIndex = CurrentPage;
            cmdPrev.Visible = !objPds.IsFirstPage;
            cmdNext.Visible = !objPds.IsLastPage;
            rpt.DataSource = objPds;
            rpt.DataBind();
        }
        public static string WordCut(string text, int cutOffLength, char[] separators)
        {
            cutOffLength = cutOffLength > text.Length ? text.Length : cutOffLength;
            int separatorIndex = text.Substring(0, cutOffLength).LastIndexOfAny(separators);
            if (separatorIndex > 0)
                return text.Substring(0, separatorIndex);
            return text.Substring(0, cutOffLength);
        }
        public static String Address
        {
            get
            {
                SmtpSection cfg = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
                return cfg.Network.UserName;
            }
        }
        public static String Pass
        {
            get
            {
                SmtpSection cfg = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
                return cfg.Network.Password;
            }
        }
        public static void sendsMail(String name, String bd, string title)
        {
            string i = DateTime.Now.ToString();

            SmtpClient SmtpServer = new SmtpClient();
            SmtpServer.Credentials = new System.Net.NetworkCredential(Address, Pass);
            SmtpServer.Port = 587;
            SmtpServer.Host = "Smtp.gmail.com";
            SmtpServer.EnableSsl = true;
            MailMessage mail = new MailMessage();
            String addr = new sysConfigBL().Select(new sysConfigDO { ConfigID = 7 }).ConfigValue.ToString();

            try
            {
                mail.From = new MailAddress(addr, name, System.Text.Encoding.UTF8);
                mail.To.Add(addr);
                //Lấy danh sách gửi kèm ở đây....
                mail.Subject = title;
                mail.Body = bd;
                mail.IsBodyHtml = true;
                mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
                SmtpServer.Send(mail);
            }
            catch (Exception ex)
            {
            }
        }
        //public static void sendsMail(String name, String bd, string title, string Bcc)
        //{
        //    string i = DateTime.Now.ToString();

        //    SmtpClient SmtpServer = new SmtpClient();
        //    SmtpServer.Credentials = new System.Net.NetworkCredential(Address, Pass);
        //    SmtpServer.Port = 587;
        //    SmtpServer.Host = "Smtp.gmail.com";
        //    SmtpServer.EnableSsl = true;
        //    MailMessage mail = new MailMessage();
        //    String addr = new sysConfigBL().Select(new sysConfigDO { ConfigID = 7 }).ConfigValue.ToString();

        //    try
        //    {
        //        mail.From = new MailAddress(addr, name, System.Text.Encoding.UTF8);
        //        mail.To.Add(addr);
        //        mail.Bcc.Add(Bcc);
        //        //Lấy danh sách gửi kèm ở đây....
        //        mail.Subject = title;
        //        mail.Body = bd;
        //        mail.IsBodyHtml = true;
        //        mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
        //        SmtpServer.Send(mail);
        //    }
        //    catch (Exception ex)
        //    {
        //    }
        //}
        public static List<string> getBCCAccount(string adminMail)
        {
            List<string> listBCC = new List<string>();
            sysConfigDO objConfig = new sysConfigBL().Select(new sysConfigDO { ConfigID = 39 });
            if (objConfig != null)
            {
                if (!string.IsNullOrEmpty(objConfig.ConfigValue))
                {
                    if (Ultility.IsJson(objConfig.ConfigValue))
                    {
                        JavaScriptSerializer objJSSerializer = new JavaScriptSerializer();
                        listBCC = objJSSerializer.Deserialize<List<string>>(objConfig.ConfigValue);
                    }
                }
            }
            listBCC.Add("tuyenbuiqn@gmail.com");
            listBCC.Add(adminMail);
            return listBCC;
        }
        public static void sendsMail(String name, String bd, string title, string customerMail)
        {
            string i = DateTime.Now.ToString();

            SmtpClient SmtpServer = new SmtpClient();
            SmtpServer.Credentials = new System.Net.NetworkCredential(Address, Pass);
            SmtpServer.Port = 587;
            SmtpServer.Host = "Smtp.gmail.com";
            SmtpServer.EnableSsl = true;
            MailMessage mail = new MailMessage();
            String addr = new sysConfigBL().Select(new sysConfigDO { ConfigID = 7 }).ConfigValue.ToString();

            try
            {
                mail.From = new MailAddress(addr, name, System.Text.Encoding.UTF8);
                mail.To.Add(customerMail);
                List<string> lstEmail = getBCCAccount(addr);
                //mail.Bcc.Add(getBCCAccount(addr));
                foreach (var item in lstEmail)
                {
                    mail.Bcc.Add(item);
                }
                //Lấy danh sách gửi kèm ở đây....
                mail.Subject = title;
                mail.Body = bd;
                mail.IsBodyHtml = true;
                mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
                SmtpServer.Send(mail);
            }
            catch (Exception ex)
            {
            }
        }
        public static bool SendMailX(string fromDisplayName, string subject, string body)
        {
            string fromAddress = "no-reply@ses.vn";
            string fromPassWord = "@@ses123";
            string toAddress = new sysConfigBL().Select(new sysConfigDO { ConfigID = 7 }).ConfigValue.ToString();
            //--Tạo mail -----------------------------------------------------|
            MailMessage msg = new MailMessage();
            msg.To.Add(toAddress);
            msg.From = new MailAddress(fromAddress, fromDisplayName,
                System.Text.Encoding.UTF8);
            msg.Subject = subject;
            msg.SubjectEncoding = System.Text.Encoding.UTF8;
            msg.Body = body;
            msg.BodyEncoding = System.Text.Encoding.UTF8;
            //--Cho phép gửi mã HTML trong mail ------------------------------|
            msg.IsBodyHtml = true;
            //--Độ ưu tiên của mail ------------------------------------------|
            msg.Priority = MailPriority.High;
            //--Chứng thực bao gồm username + password -----------------------|
            SmtpClient client = new SmtpClient();
            client.Credentials = new System.Net.NetworkCredential
            (fromAddress, fromPassWord);
            //--Cổng 587 của server SMTP Google để gửi mail-------------------|
            client.Port = 587;
            //--Địa chỉ server SMTP của google -------------------------------|
            client.Host = "smtp.gmail.com";
            //--Sử dụng mã hóa đường truyền SSL (Secure Sockets Layer)--------|
            client.EnableSsl = true;
            //--Bắt đầu quá trình gửi mail -----------------------------------|
            try { client.Send(msg); } //--Gửi mail--| 
            catch { return false; } //--Không thể gửi mail     
            return true; //--Gửi mail thành công
        }
        public static string Breadcrumb(string page, string keyword)
        {
            string root = "<li class=\"first\"><a href=\"/\" title=\"Trang chủ\" style=\"z-index:10;\"><span></span>Trang chủ</a></li>";
            switch (page)
            {
                case "search":
                    {
                        root += "<li class=><a href=\"/tim-kiem/" + keyword + "\" title=\"Tìm kiếm\" style=\"z-index:9;\"><span></span>Tìm kiếm - " + keyword + "</a></li>";
                    }
                    break;
            }
            return root;
        }
        public static string Breadcrumb(string page, int id)
        {
            cmsCategoryDO objCate = new cmsCategoryDO();
            cmsCategoryBL cateBL = new cmsCategoryBL();
            string root = "<li class=\"first\"><a href=\"/\" title=\"Trang chủ\" style=\"z-index:10;\"><span></span>Trang chủ</a></li>";
            switch (page)
            {
                case "article":
                    {
                        if (id > 0)
                        {
                            cmsArticleDO objArt = new cmsArticleDO();
                            objArt.ArticleID = id;

                            objArt = new cmsArticleBL().Select(objArt);
                            objCate.CategoryID = objArt.CategoryID;
                            objCate = cateBL.Select(objCate);

                            if (objCate != null)
                            {
                                root += "<li><a href=\"" + "/danh-muc-tin/" + Change_AV(objCate.Title) + "-" + objCate.CategoryID + "\" title=\"" + objCate.Title + "\" style=\"z-index:9;\"><span></span>" + objCate.Title + "</a></li>";
                                root += "<li><a href=\"" + "/bai-viet/" + Change_AV(objArt.Title) + "-" + objArt.ArticleID + "\" title=\"" + objArt.Title + "\" style=\"z-index:8;\"><span></span>" + objArt.Title + "</a></li>";
                            }

                        }
                    }
                    break;
                case "category":
                    {
                        if (id > 0)
                        {
                            objCate.CategoryID = id;
                            objCate = cateBL.Select(objCate);
                            if (objCate != null)
                            {
                                root += "<li><a href=\"" + "/danh-muc-tin/" + Change_AV(objCate.Title) + "-" + objCate.CategoryID + "\" title=\"" + objCate.Title + "\" style=\"z-index:9;\"><span></span>" + objCate.Title + "</a></li>";
                            }
                        }
                    }
                    break;
                case "product":
                    {
                        root += "<li class=\"\"><a href=\"/danh-muc-san-pham/\" title=\"Danh mục sản phẩm\" style=\"z-index:9;\"><span></span>Sản phẩm</a></li>";
                        if (id > 0)
                        {
                            cmsProductDO objProduct = new cmsProductBL().Select(new cmsProductDO { ProductID = id });

                            if (objProduct != null)
                            {
                                cmsProductCategoryDO objProCate = new cmsProductCategoryBL().Select(new cmsProductCategoryDO { ProductCategoryID = objProduct.ProductCategoryID });

                                root += "<li><a href=\"" + "/danh-muc-san-pham/" + Change_AV(objProCate.ProductCategoryTitle) + "-" + objProCate.ProductCategoryID + "\" title=\"" + objProCate.ProductCategoryTitle + "\" style=\"z-index:8;\"><span></span>" + objProCate.ProductCategoryTitle + "</a></li>";
                                root += "<li><a href=\"" + "/san-pham/" + Change_AV(objProduct.ProductTitle) + "-" + objProduct.ProductID + "\" title=\"" + objProduct.ProductTitle + "\" style=\"z-index:7;\"><span></span>" + objProduct.ProductTitle + "</a></li>";
                            }

                        }
                    }
                    break;
                case "productcategory":
                    {
                        if (id > 0)
                        {
                            root += "<li class=\"\"><a href=\"/danh-muc-san-pham/\" title=\"Danh mục sản phẩm\" style=\"z-index:9;\"><span></span>Sản phẩm</a></li>";

                            cmsProductCategoryDO objProCate = new cmsProductCategoryBL().Select(new cmsProductCategoryDO { ProductCategoryID = id });
                            if (objProCate != null)
                            {
                                root += "<li><a href=\"" + "/danh-muc-san-pham/" + Change_AV(objProCate.ProductCategoryTitle) + "-" + objProCate.ProductCategoryID + "\" title=\"" + objProCate.ProductCategoryTitle + "\" style=\"z-index:8;\"><span></span>" + objProCate.ProductCategoryTitle + "</a></li>";
                            }
                        }
                        else
                        {
                            root += "<li class=\"\"><a href=\"/danh-muc-san-pham/\" title=\"Danh mục sản phẩm\" style=\"z-index:9;\"><span></span>Sản phẩm</a></li>";
                        }
                    }
                    break;
                default:
                    break;
            }

            return root;
        }
        public static long TimeStamp()
        {
            return (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
        }
        public static bool IsJson(string input)
        {
            input = input.Trim();
            return input.StartsWith("{") && input.EndsWith("}")
                   || input.StartsWith("[") && input.EndsWith("]");
        }
        public static void ClearCache()
        {
            Cache cache = HttpContext.Current.Cache;
            cache.Remove("HomeProducts");
            cache.Remove("HomeNew");
            cache.Remove("HomePromotion");
            cache.Remove("HomeCategories");
        }
        public static void ClearAllCache()
        {
            Cache cache = HttpContext.Current.Cache;
            List<string> keys = new List<string>();
            // retrieve application Cache enumerator
            IDictionaryEnumerator enumerator = cache.GetEnumerator();
            // copy all keys that currently exist in Cache
            while (enumerator.MoveNext())
            {
                keys.Add(enumerator.Key.ToString());
            }
            // delete every key from cache
            for (int i = 0; i < keys.Count; i++)
            {
                cache.Remove(keys[i]);
            }

        }
        public static string GetSort(string sort)
        {
            string sortBy = "";
            if (sort.Equals(""))
            { sortBy = "productid desc"; }
            else if (sort.Equals("prd"))
            {
                sortBy = "price desc";
            }
            else if (sort.Equals("pra"))
            {
                sortBy = "price asc";
            }
            else if (sort.Equals("proa"))
            {
                sortBy = "productid asc";
            }
            else if (sort.Equals("prod"))
            {
                sortBy = "productid desc";
            }
            return sortBy;
        }

    }
}
